package com.infinitus.activity.util;

import com.infinitus.activity.model.ActivityLog;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * * @class         : ActivityLog（类名）
 * @Package       : utils
 * @author        : zhangxh
 * @create        : 2017年1月3日 下午3:32:06 （创建日期 时间）
 * @desription   : 活动日志保存
 * @version       : v2.0（版本号）
 */
public class ActivityLogUtil {
    //获取数据库链接
    private Connection getConnection(){
        return ConnectionUtil.getConnection();
    }

    /**
     *
     * @Title: saveLog
     * @Description: 保存日志
     * @author    add   by zhangxh 2017年1月3日 下午4:16:44
     * @param log
     * @return
     * @throws
     *
     */
    public String saveLog(ActivityLog log){
        String result = "{'code':200,'data':[{'保存成功'}]}";
        StringBuilder sql = new StringBuilder();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
        Date date=new Date();
        String str=sdf.format(date);
        Integer day = Integer.parseInt(str);
        String tableName = "nx_activity_"+PropertiesUtil.getConfigInfo().getProperty("activity.id")+"_count";
        sql.append("insert into ").append(tableName).append("(c_id,ip,agent,type,add_time,day_a) values (?,?,?,?,?,?)");
        //sql.append("insert into ").append(tableName).append("(c_id,ip,agent,type,add_time,day_a) values (?,?,?,?,?,?)");
        //sql.append("insert into ").append(tableName).append("(c_id,ip,agent,type,add_time,day)values(")
        //.append(log.getcId()+",'").append(log.getIp()+"','").append(log.getAgent()).append("',").append(log.getType()).append(",").append(System.currentTimeMillis())
        //.append(",").append(day).append(")");
        //System.out.println("========="+sql.toString());
        try {
            Connection con = getConnection();
            PreparedStatement ps = con.prepareStatement(sql.toString());
            ps.setInt(1, log.getcId());
            ps.setString(2, log.getIp());
            ps.setString(3, log.getAgent());
            ps.setInt(4, log.getType());
            ps.setLong(5,System.currentTimeMillis());
            ps.setInt(6, day);
            ps.executeUpdate();
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw, true));
            String strs = sw.toString();
            result = "{'code':400,'data':[{'"+strs+"'}]}";
            //System.out.println(strs);
        }
        return result;
    }
}